package core

import (
	"fmt"

	"gitee.com/krio/ginc/example/core/lib/conf"
	"gitee.com/krio/ginc/example/router/bind"
	"gitee.com/krio/ginc/example/router/middleware"
	"gitee.com/krio/ginc/example/util/cmdprint"
	"github.com/gin-gonic/gin"
)

// ApiEngine api引擎
type ApiEngine struct {
	*gin.Engine
}

// InitApiRouter 注册Api路由
func InitApiRouter() ApiEngine {
	engine := initEngine()
	// 设置pprof
	engine.SetPprof()
	// swagger文档
	engine.SetSwagger()
	// 设置全局中间件
	engine.SetOverallMiddleware()
	// api路由绑定处理
	bind.ApiBind(engine.Engine)

	cmdprint.CmdSuccess(fmt.Sprintf("服务: %s|%s|%s|%s", conf.C.App.AppID, conf.C.App.AppName, conf.C.App.AppDesc, conf.C.App.AppEnv))
	cmdprint.CmdSuccess(fmt.Sprintf("接口: :%d", conf.C.Gin.Port))
	cmdprint.CmdSuccess(fmt.Sprintf("后台: http://localhost:%d/admin/login", conf.C.Gin.Port))
	cmdprint.CmdSuccess(fmt.Sprintf("文档: http://localhost:%d/doc/swagger/index.html", conf.C.Doc.Port))
	cmdprint.CmdSuccess(fmt.Sprintf("pprof: http://localhost:%d/debug/pprof", conf.C.Gin.Port))

	return engine
}

// SetOverallMiddleware 设置全局中间件
func (engine ApiEngine) SetOverallMiddleware() {
	engine.Use(
		middleware.Recover, // 全局异常处理
		middleware.Cors,    // 跨域
		middleware.Tracer,  // 链路追踪
	)
}

// SetPprof 设置Go性能分析工具pprof
func (engine ApiEngine) SetPprof() {
	//pprof.Register(engine.Engine)
}

// 初始化api引擎
func initEngine() ApiEngine {
	gin.SetMode(conf.C.Gin.Mode) // 全局设置环境
	g := gin.Default()           // 获得路由实例
	return ApiEngine{Engine: g}
}
